package com.rising.online.bean;

import javax.tools.SimpleJavaFileObject;
import java.io.ByteArrayOutputStream;
import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URI;

/**
 * @Description   : java文件对象，保存源文件和编译后的class文件流
 * @Auther        : rising
 * @CreateDate    : 2019-09-16 23:13
 */
public class DynamicCompileJavaFileObject extends SimpleJavaFileObject {
    private String code;
    private ByteArrayOutputStream outputStream;
    private String name;
    private CompilerBean compilerBean;


    /**
     * 编译文件前需要
     * @param className
     * @param code
     */
    public DynamicCompileJavaFileObject(String className, String code) {
        super(URI.create("String:///" + className.replaceAll("\\.", "/") + Kind.SOURCE.extension), Kind.SOURCE);
        this.code = code;
        this.name = className;
    }

    public DynamicCompileJavaFileObject(CompilerBean compilerBean, String className, Kind kind) {
        super(URI.create("String:///" + className.replaceAll("\\.", "/") + Kind.SOURCE.extension), kind);
        this.name = className;
        this.compilerBean = compilerBean;
    }

    @Override
    public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException {
        if (code == null) {
            throw new IllegalArgumentException("code required");
        }
        return code;
    }

    @Override
    public OutputStream openOutputStream() throws IOException {
        return new FilterOutputStream(new ByteArrayOutputStream()) {
            @Override
            public void close() throws IOException {
                out.close();
                ByteArrayOutputStream bos = (ByteArrayOutputStream) out;
                compilerBean.getClassBytes().put(name, bos.toByteArray());
            }
        };
    }
}
